<?php
class UsersController extends AppController {
	public $name = 'Users';
	public $uses=array('User','Group');
	public $components=array('Acl');
	function admin_atest(){}
	function profile(){
		$this->layout='default';
		$error=0;
		$user=$this->Auth->user();
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				//get user info
				$data=$this->{$this->uses[0]}->findById($user['User']['id']);			
				
				$oldpass = $this->data[$this->uses[0]]['oldpass'];
				$newpass = $this->data[$this->uses[0]]['newpass'];
				$confirmpass = $this->data[$this->uses[0]]['confirmpass'];
				//check new pass
				if(!empty($newpass)){
					$error=1;
					if($this->Auth->password($oldpass)!=$data['User']['password']){
						$this->Session->write('error',_resource('old password is not correct'));						
					}elseif($newpass!=$confirmpass){
						$this->Session->write('error',_resource('confirm password is not correct'));
					}else{
						//build save data
						$error=0;						
						$this->data[$this->uses[0]]['password']=$this->Auth->password($newpass);												
					}						
				}
				if(!$error){
					$this->data[$this->uses[0]]['username']=$data['User']['username'];
					$this->data[$this->uses[0]]['group_id ']=$data['User']['group_id'];
					//save
					if($this->{$this->uses[0]}->save($this->data)) {						
						$this->Session->write('message',_resource('update data successful',true));					
					}
				}					
			}else{
				$this->Session->write('error',_resource('red fill is require'));
			}
		}else{
			if($user['User']['id']!=null){
				$this->data=$this->{$this->uses[0]}->findById($user['User']['id']);	
				if(empty($this->data)){		
					$this->Session->write('error',_resource('data not found',true));			
					$this->render('editNotFound');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('admin_edit_not_found');
			}
		}	
	
		
	}
	function login(){
		$this->render('login');
	}
	function admin_login(){	
		//$this->User->save(array('User'=>array('password'=>'admin','username'=>'test')));
		//debug($this->Auth->login());
		$data=$this->User->find('first');		
		//t($data);
		if ($this->Auth->login()) {
        	$this->redirect($this->Auth->loginRedirect);
	    } else {
	    	if($this->request->is('post')) $this->Session->write('error',_resource('Invalid username or password, try again'));
	    }
			
		
	}
	function logout(){	
		if(count($_SESSION)>0){
			foreach($_SESSION as $k=>$v){
				unset($_SESSION[$k]);
			}
		}
		$this->redirect(SITE_URL);
	}
	function admin_logout(){
		if(count($_SESSION)>0){
			foreach($_SESSION as $k=>$v){
				unset($_SESSION[$k]);
			}
		}
		$this->redirect($this->Auth->logout());
	}
	function admin_index(){
		//get filter field
		$filterField=array(				
			$this->uses[0].'.username'=>_resource('username',true),	
		);
		$this->set('filterField',$filterField);
	}	
	
	function admin_lists(){
		//init session
		if(!$this->Session->check($this->uses[0].'.limit')){
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>array($this->uses[1].'.site_id'=>2),
				'fields'=>null,
				'order'=>null,
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			$this->Session->write($this->uses[0],$tmp);			
		}
		
		
		//get data
		
		$this->paginate=$this->Session->read($this->uses[0]);		
		//$this->paginate['conditions'][$this->uses[1].'.sited_id']=2;
		//t($this->paginate);
		$data0=$this->paginate($this->uses[0]);
		//t($data0);
		$this->set('data0',$data0);
		$this->render('admin_lists','ajax');
	}
	
	function admin_add(){
		$this->{$this->uses[0]}->recursive=0;
		$name_error=_resource('can not be null',true);
		$email_error=_resource('invalid email',true);
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				$data=$this->{$this->uses[0]}->findByUsername($this->data[$this->uses[0]]['username']);
				if($data){
					$this->Session->write('error',_resource('error',true));
					$name_error= _resource('duplicate data',true);
					$this->{$this->uses[0]}->invalidate('username');
				} elseif ($this->{$this->uses[0]}->findByEmail($this->data[$this->uses[0]]['email'])) {
					$this->Session->write('error',_resource('error',true));
					$email_error= _resource('duplicate email',true);
					$this->{$this->uses[0]}->invalidate('email');
					}else{
						if(!intval($this->data[$this->uses[0]]['group_id'])){
							$this->Session->write('error',_resource('please choice user group',true));
						}
						else{
							$this->data[$this->uses[0]]['username']=htmlspecialchars($this->data[$this->uses[0]]['username']);
							$this->data['User']['password'] = $this->Auth->password($this->webConfig['default_password']);
							if($this->{$this->uses[0]}->save($this->data)) {
								$this->data=null;
								$isInsert=true;
								$this->Session->write('message',_resource('insert user successful with password \"'.$this->webConfig['default_password'].'\"',true));				
								
							} else {
								$this->Session->write('error',_resource('can not insert data',true));
							}
						}
					}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}
		
		$this->set('groups',$this->{$this->uses[1]}->find('list',array('conditions'=>array($this->uses[1].'.site_id'=>2))));
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
		$this->set('email_error',$email_error);
		$this->render('admin_add','ajax');
	}

	function admin_edit($id=null){
		$this->{$this->uses[0]}->recursive=0;
		$name_error=_resource('can not be null',true);
		$email_error=_resource('invalid email',true);
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->validates($this->data)){
				$data=$this->{$this->uses[0]}->findByUsername($this->data[$this->uses[0]]['username']);
				$email=$this->{$this->uses[0]}->findByEmail($this->data[$this->uses[0]]['email']);
				if($data && $data[$this->uses[0]]['id']!=$this->data[$this->uses[0]]['id']){
					$this->Session->write('error',_resource('error',true));
					$name_error= _resource('duplicate data',true);
					$this->{$this->uses[0]}->invalidate('username');
				} elseif ($email && $email[$this->uses[0]]['email']!=$this->data[$this->uses[0]]['email']) {
					$this->Session->write('error',_resource('error',true));
					$email_error= _resource('duplicate email',true);
					$this->{$this->uses[0]}->invalidate('email');
					}else{						
						$this->data[$this->uses[0]]['username']=htmlspecialchars($this->data[$this->uses[0]]['username']);
						$this->data[$this->uses[0]]['password']=$data[$this->uses[0]]['password'];
						$oldgroupid = $this->{$this->uses[0]}->field('group_id');
						if(!intval($this->data[$this->uses[0]]['group_id'])){
							$this->Session->write('error',_resource('please choice user group',true));
						}
						else{
							if($this->{$this->uses[0]}->save($this->data)) {
								if ($oldgroupid !== $this->data[$this->uses[0]]['group_id']) {
									$aro =& $this->Acl->Aro;
									
									$user = $aro->find('first',array('conditions'=>array('foreign_key'=>$this->data[$this->uses[0]]['id'],'model'=> $this->uses[0])));
									$group = $aro->find('first',array('conditions'=>array('foreign_key'=>$this->data[$this->uses[0]]['group_id'],'model'=> $this->uses[1])));							
									
									// Save to ARO table
									$aro->id = $user['Aro']['id'];
									$aro->save(array('parent_id' => $group['Aro']['id']));
								}
								$this->data=null;
								$isInsert=true;
								$this->set('listGroup',$this->{$this->uses[1]}->find('list'));
								$this->Session->write('message',_resource('update data successful',true));						
								
							} else {
								$this->Session->write('error',_resource('can not update data',true));
							}
						}
					}
			}else{
				$this->Session->write('error',_('red fill is require'));
			}
		}else{
			if($id!=null){
				$this->data=$this->{$this->uses[0]}->findById($id);					
				if(empty($this->data)){		
					$this->Session->write('error',_resource('data not found',true));			
					$this->render('editNotFound');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('admin_edit_not_found');
			}
		}		
		$this->set('groups',$this->{$this->uses[1]}->find('list',array('conditions'=>array($this->uses[1].'.site_id'=>2))));
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
		$this->set('email_error',$email_error);
		$this->render('admin_edit','ajax');
	}
	
	function admin_edit_profile(){
		$user=$this->Auth->user();
		$name_error=_resource('can not be null',true);
		$email_error=_resource('invalid email',true);
		$error=0;
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				//get user info
				$data=$this->{$this->uses[0]}->findById($user['id']);			
				
				$oldpass = $this->data[$this->uses[0]]['oldpass'];
				$newpass = $this->data[$this->uses[0]]['newpass'];
				$confirmpass = $this->data[$this->uses[0]]['confirmpass'];
				//check new pass
				if(!empty($newpass)){
					$error=1;
					if($this->Auth->password($oldpass)!=$data['User']['password']){
						$this->Session->write('error',_resource('old password is not correct',true));						
					}elseif($newpass!=$confirmpass){
						$this->Session->write('error',_resource('confirm password is not correct',true));
					}else{
						//build save data
						$error=0;			
						$data[$this->uses[0]]['name']=$this->data[$this->uses[0]]['name'];
						$data[$this->uses[0]]['email']=$this->data[$this->uses[0]]['email'];	
						$data[$this->uses[0]]['password']=$this->Auth->password($newpass);
												
					}						
				}
				if(!$error){
					
					$this->data[$this->uses[0]]['username']=$data['User']['username'];
					$this->data[$this->uses[0]]['group_id ']=$data['User']['group_id'];
					//save
					
					if($this->{$this->uses[0]}->save($data)) {						
						$this->Session->write('message',_resource('update data successful',true));					
					}
				}					
			}else{
				$this->Session->write('error',_resource('red fill is require'));
			}
		}else{
			if($user['id']!=null){
				
				$this->data=$this->{$this->uses[0]}->findById($user['id']);	
				if(empty($this->data)){		
					$this->Session->write('error',_resource('data not found',true));			
					$this->render('editNotFound');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('admin_edit_not_found');
			}
		}		
		
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
		$this->set('email_error',$email_error);
		$this->render('admin_edit_profile','ajax');
	}

	function admin_delete($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('delete from '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' where id in ('.implode(',',array_keys($id_arr)).')' );			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();		
	}
	
	function admin_reset($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			
				if(!$this->{$this->uses[0]}->updateAll(array($this->uses[0].'.password'=>'"'.$this->Auth->password($this->webConfig['default_password']).'"'),array($this->uses[0].'.id'=>array_keys($id_arr)))){
					$this->Session->write('error',_('error'));
				}
				
			
			if(!$this->Session->check('error')){
				$this->Session->write('message',_resource('password reset to \"'.$this->webConfig['default_password'].'\"',true));
			}
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();		
	}
	
	function admin_published($id=null,$value=1,$field=0){
		$id_arr=null;
		$all=false;		
		switch($field){
			case 1: $fieldname='best';break;
			case 2: $fieldname='bestbuy';break;
			default: $fieldname='published';
		}
		if((!intval($value) && $value!=0) || intval($value)>1){
			$value=1;
		}
		
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
			$all=true;
		} 
		
		//if url
		if(intval($id) && !$all){
			$id_arr[$id]='';
		}
		
		if(count($id_arr)>0){			
			$this->{$this->uses[0]}->query('update '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' set '.$fieldname.'='.$value.' where id in ('.implode(',',array_keys($id_arr)).')' );
		}
		if (!$all) {			
			$this->set('value',$value);
			$this->set('field',$field);
			$this->set('fieldname',$fieldname);
			$this->set('id',intval($id));
			$this->render('admin_published','ajax');		
		} else {
			$this->admin_lists();
		}
		
	}
	
	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}
	
	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists();
	}
	
	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}	
	

	//===========================================================

	

}
?>
